// component/calendar/calendar.js
import {
    GET_HOSPITAL_SCHEDULES
} from '~/http/interfaces'
import {
    getStorageSync
} from '~/utils/util'
import moment from 'moment'
var touchStartX = 0; //触摸时的原点  
var touchStartY = 0; //触摸时的原点  
var time = 0; // 时间记录，用于滑动时且时间小于1s则执行左右滑动  
var interval = ""; // 记录/清理时间记录  
var touchMoveX = 0; // x轴方向移动的距离
var touchMoveY = 0; // y轴方向移动的距离
Component({
    /**
     * 组件的属性列表
     */
    properties: {
        spotMap: {
            //标点的日期
            type: Object,
            value: {},
        },
        defaultTime: {
            //标记的日期，默认为今日 注意：传入格式推荐为'2022/1/2'或'2022/01/02', 其他格式在ios系统上可能出现问题
            type: String,
            value: '',
        },
        title: {
            //标题
            type: String,
            value: '',
        },
        goNow: {
            // 是否有快速回到今天的功能
            type: Boolean,
            value: true,
        },
        defaultOpen: {
            // 是否是打开状态
            type: Boolean,
            value: false,
        },
        showShrink: {
            // 是否显示收缩展开功能
            type: Boolean,
            value: true,
        },
        disabledDate: {
            // 指定不可用日期
            type: Function,
            value: undefined,
        },
        // changeTime: {
        //     // 要改变的日期
        //     type: String,
        //     value: '',
        // },
    },

    /**
     * 组件的初始数据
     */
    data: {
        selectDay: {}, //选中的日期
        nowDay: {}, //现在的日期
        disabledDate: {}, //禁用的日期
        open: true,
        swiperCurrent: 1, //选中的日期
        oldCurrent: 1, //之前选中的日期
        dateList0: [], //0位置的日历数组
        dateList1: [], //1位置的日历数组
        dateList2: [], //2位置的日历数组
        swiperDuration: 500,
        swiperHeight: 0,
        backChange: false, //跳过change切换
        disabledDateList: {}, //禁用的日期集合

        scheduList: {},
        classNameList: {
            5: "blue", // 待到店,
            4: "orange", // 已改约,
            6: "grey", // 已取消,
            8: "green", //已成交
            7: "red", //未成交
        },
        currentSelect: '',
        today: '',
        showPopup: false,
        // pickerTime: new Date().getTime(),
        currentMonth: new Date().getTime(),
        showCurrentMonth: ''
    },

    /**
     * 组件的方法列表
     */
    methods: {
        // // 日历滑动时触发的方法
        // swiperChange(e) {
        //     if (this.data.backChange) {
        //         this.setData({
        //             backChange: false,
        //         });
        //         return;
        //     }
        //     //计算第三个索引
        //     let rest = 3 - e.detail.current - this.data.oldCurrent;
        //     let dif = e.detail.current - this.data.oldCurrent;
        //     let date;
        //     if (dif === -2 || (dif > 0 && dif !== 2)) {
        //         //向右划的情况，日期增加
        //         if (this.data.open) {
        //             date = new Date(this.data.selectDay.year, this.data.selectDay.month);
        //             this.setMonth(date.getFullYear(), date.getMonth() + 1, undefined);
        //             this.getIndexList({
        //                 setYear: this.data.selectDay.year,
        //                 setMonth: this.data.selectDay.month,
        //                 dateIndex: rest,
        //             });
        //         } else {
        //             date = new Date(
        //                 this.data.selectDay.year,
        //                 this.data.selectDay.month - 1,
        //                 this.data.selectDay.day + 7
        //             );
        //             this.setMonth(
        //                 date.getFullYear(),
        //                 date.getMonth() + 1,
        //                 date.getDate()
        //             );
        //             this.getIndexList({
        //                 setYear: this.data.selectDay.year,
        //                 setMonth: this.data.selectDay.month - 1,
        //                 setDay: this.data.selectDay.day + 7,
        //                 dateIndex: rest,
        //             });
        //         }
        //     } else {
        //         //向左划的情况，日期减少
        //         if (this.data.open) {
        //             date = new Date(
        //                 this.data.selectDay.year,
        //                 this.data.selectDay.month - 2
        //             );
        //             this.setMonth(date.getFullYear(), date.getMonth() + 1, undefined);
        //             this.getIndexList({
        //                 setYear: this.data.selectDay.year,
        //                 setMonth: this.data.selectDay.month - 2,
        //                 dateIndex: rest,
        //             });
        //         } else {
        //             date = new Date(
        //                 this.data.selectDay.year,
        //                 this.data.selectDay.month - 1,
        //                 this.data.selectDay.day - 7
        //             );
        //             this.setMonth(
        //                 date.getFullYear(),
        //                 date.getMonth() + 1,
        //                 date.getDate()
        //             );
        //             this.getIndexList({
        //                 setYear: this.data.selectDay.year,
        //                 setMonth: this.data.selectDay.month - 1,
        //                 setDay: this.data.selectDay.day - 7,
        //                 dateIndex: rest,
        //             });
        //         }
        //     }
        //     this.setData({
        //         oldCurrent: e.detail.current,
        //     });
        //     this.setSwiperHeight(e.detail.current);
        // },

        // 根据指定位置数组的大小计算日历的高度
        setSwiperHeight(index) {
            this.setData({
                swiperHeight: (this.data[`dateList${index}`].length / 7) * 98 + 18,
            });
        },

        // 更新指定的索引和月份的列表
        getIndexList({
            setYear,
            setMonth,
            setDay = void 0,
            dateIndex
        }) {
            let appointMonth;
            if (setDay) appointMonth = new Date(setYear, setMonth, setDay);
            else appointMonth = new Date(setYear, setMonth);
            const listName = `dateList${dateIndex}`;
            const dataList = this.dateInit({
                setYear: appointMonth.getFullYear(),
                setMonth: appointMonth.getMonth() + 1,
                setDay: appointMonth.getDate(),
                hasBack: true,
            });
            const disabledDateList = {};
            if (this.data.disabledDate)
                dataList.forEach((item) => {
                    if (
                        !this.data.disabledDateList[
                            `disabled${item.year}M${item.month}D${item.day}`
                        ] &&
                        this.data.disabledDate(item)
                    ) {
                        disabledDateList[
                            `disabled${item.year}M${item.month}D${item.day}`
                        ] = true;
                    }
                });
            console.log(dataList[1])
            this.setData({
                [listName]: dataList,
                disabledDateList: Object.assign(
                    this.data.disabledDateList,
                    disabledDateList
                ),
            });
        },
        // 设置月份
        setMonth(setYear, setMonth, setDay) {
            const day = Math.min(
                new Date(setYear, setMonth, 0).getDate(),
                this.data.selectDay.day
            );
            if (
                this.data.selectDay.year !== setYear ||
                this.data.selectDay.month !== setMonth
            ) {
                const data = {
                    selectDay: {
                        year: setYear,
                        month: setMonth,
                        day: setDay ? setDay : day,
                    },
                };
                if (!setDay) {
                    data.open = true;
                }
                this.setData(data, () => {
                    this.triggerEventSelectDay();
                });
            } else {
                const data = {
                    selectDay: {
                        year: setYear,
                        month: setMonth,
                        day: setDay ? setDay : day,
                    },
                };
                this.setData(data, () => {
                    this.triggerEventSelectDay();
                });
            }
        },
        // 展开收起
        // openChange() {
        //     this.setData({
        //         open: !this.data.open,
        //     });
        //     // 更新数据
        //     const selectDate = new Date(
        //         this.data.selectDay.year,
        //         this.data.selectDay.month - 1,
        //         this.data.selectDay.day
        //     );
        //     if (this.data.oldCurrent === 0) {
        //         this.updateList(selectDate, -1, 2);
        //         this.updateList(selectDate, 0, 0);
        //         this.updateList(selectDate, 1, 1);
        //     } else if (this.data.oldCurrent === 1) {
        //         this.updateList(selectDate, -1, 0);
        //         this.updateList(selectDate, 0, 1);
        //         this.updateList(selectDate, 1, 2);
        //     } else if (this.data.oldCurrent === 2) {
        //         this.updateList(selectDate, -1, 1);
        //         this.updateList(selectDate, 0, 2);
        //         this.updateList(selectDate, 1, 0);
        //     }
        //     this.setSwiperHeight(this.data.oldCurrent);
        // },
        // 选中并切换今日日期
        // witchDate(setDate) {
        //     const selectDate = new Date(
        //         this.data.selectDay.year,
        //         this.data.selectDay.month - 1,
        //         this.data.selectDay.day
        //     );
        //     let dateDiff =
        //         (selectDate.getFullYear() - setDate.getFullYear()) * 12 +
        //         (selectDate.getMonth() - setDate.getMonth());
        //     let diff = dateDiff === 0 ? 0 : dateDiff > 0 ? -1 : 1;
        //     const diffSum = (x) => (3 + (x % 3)) % 3;
        //     if (this.data.oldCurrent === 0) {
        //         this.updateList(setDate, -1, diffSum(2 + diff));
        //         this.updateList(setDate, 0, diffSum(0 + diff));
        //         this.updateList(setDate, 1, diffSum(1 + diff));
        //     } else if (this.data.oldCurrent === 1) {
        //         this.updateList(setDate, -1, diffSum(0 + diff));
        //         this.updateList(setDate, 0, diffSum(1 + diff));
        //         this.updateList(setDate, 1, diffSum(2 + diff));
        //     } else if (this.data.oldCurrent === 2) {
        //         this.updateList(setDate, -1, diffSum(1 + diff));
        //         this.updateList(setDate, 0, diffSum(2 + diff));
        //         this.updateList(setDate, 1, diffSum(0 + diff));
        //     }
        //     this.setData({
        //         swiperCurrent: diffSum(this.data.oldCurrent + diff),
        //         oldCurrent: diffSum(this.data.oldCurrent + diff),
        //         backChange: dateDiff !== 0,
        //     });
        //     this.setData({
        //             selectDay: {
        //                 year: setDate.getFullYear(),
        //                 month: setDate.getMonth() + 1,
        //                 day: setDate.getDate(),
        //             },
        //         },
        //         () => {
        //             this.triggerEventSelectDay();
        //         }
        //     );
        //     this.setSwiperHeight(this.data.oldCurrent);
        // },
        // 切换到今天
        // switchNowDate() {
        //     this.witchDate(new Date());
        // },
        // 日历主体的渲染方法
        dateInit({
            setYear,
            setMonth,
            setDay = this.data.selectDay.day,
            hasBack = false,
        } = {
            setYear: this.data.selectDay.year,
            setMonth: this.data.selectDay.month,
            setDay: this.data.selectDay.day,
            hasBack: false,
        }) {
            let dateList = []; //需要遍历的日历数组数据
            let now = new Date(setYear, setMonth - 1); //当前月份的1号
            let startWeek = now.getDay(); //目标月1号对应的星期
            let resetStartWeek = startWeek == 0 ? 6 : startWeek - 1; //重新定义星期将星期天替换为6其余-1
            let dayNum = new Date(setYear, setMonth, 0).getDate(); //当前月有多少天
            let forNum = Math.ceil((resetStartWeek + dayNum) / 7) * 7; //当前月跨越的周数
            let selectDay = setDay ? setDay : this.data.selectDay.day;
            this.triggerEvent('getDateList', {
                setYear: now.getFullYear(),
                setMonth: now.getMonth() + 1,
            });
            if (this.data.open) {
                //展开状态，需要渲染完整的月份
                for (let i = 0; i < forNum; i++) {
                    const now2 = new Date(now);
                    now2.setDate(i - resetStartWeek + 1);
                    let obj = {};
                    obj = {
                        day: now2.getDate(),
                        month: now2.getMonth() + 1,
                        year: now2.getFullYear(),
                        full: `${now2.getFullYear()}-${now2.getMonth() + 1}-${now2.getDate()}`
                    };
                    dateList[i] = obj;
                }
            } else {
                //非展开状态，只需要渲染当前周
                for (let i = 0; i < 7; i++) {
                    const now2 = new Date(now);
                    //当前周的7天
                    now2.setDate(
                        Math.ceil((selectDay + (startWeek - 1)) / 7) * 7 -
                        6 -
                        (startWeek - 1) +
                        i
                    );
                    let obj = {};
                    obj = {
                        day: now2.getDate(),
                        month: now2.getMonth() + 1,
                        year: now2.getFullYear(),
                        full: `${now2.getFullYear()}-${now2.getMonth() + 1}-${now2.getDate()}`
                    };
                    dateList[i] = obj;
                }
            }
            if (hasBack) {
                return dateList;
            }
            console.log(dateList)
            this.setData({
                dateList1: dateList,
            });
        },
        // 一天被点击时
        selectChange(e) {
            const year = e.currentTarget.dataset.year;
            const month = e.currentTarget.dataset.month;
            const day = e.currentTarget.dataset.day;
            const selectDay = {
                year: year,
                month: month,
                day: day,
            };
            if (
                this.data.open &&
                (this.data.selectDay.year !== year ||
                    this.data.selectDay.month !== month)
            ) {
                if (
                    year * 12 + month >
                    this.data.selectDay.year * 12 + this.data.selectDay.month
                ) {
                    // 下个月
                    if (this.data.oldCurrent == 2)
                        this.setData({
                            swiperCurrent: 0,
                        });
                    else
                        this.setData({
                            swiperCurrent: this.data.oldCurrent + 1,
                        });
                } else {
                    // 点击上个月
                    if (this.data.oldCurrent == 0)
                        this.setData({
                            swiperCurrent: 2,
                        });
                    else
                        this.setData({
                            swiperCurrent: this.data.oldCurrent - 1,
                        });
                }
                this.setData({
                        ['selectDay.day']: day,
                    },
                    () => {
                        this.triggerEventSelectDay();
                    }
                );
            } else if (this.data.selectDay.day !== day) {
                this.setData({
                        selectDay: selectDay,
                    },
                    () => {
                        this.triggerEventSelectDay();
                    }
                );
            }
        },
        // 选择某天时触发的事件
        triggerEventSelectDay() {
            if (
                !this.data.disabledDateList[
                    'disabled' +
                    this.data.selectDay.year +
                    'M' +
                    this.data.selectDay.month +
                    'D' +
                    this.data.selectDay.day
                ]
            )
                this.triggerEvent('selectDay', this.data.selectDay);
        },
        // 更新日历列表
        updateList(date, offset, index) {
            const setDate = new Date(
                date.getFullYear(),
                date.getMonth() + offset * 1
            ); //取得当前日期的上个月日期
            this.getIndexList({
                setYear: setDate.getFullYear(),
                setMonth: setDate.getMonth(),
                dateIndex: index,
            });

        },

        // 获取排班数据
        getSchedules() {
            let _this = this;
            let user = this.data.user
            let oParams = {}
            oParams.hospitalId = user.hospitalId
            console.log(moment(_this.data.currentMonth).format('YYYY-MM'))
            oParams.month = moment(_this.data.currentMonth).format('YYYY-MM')
            GET_HOSPITAL_SCHEDULES(oParams).then(res => {
                let obj = res.data || [];
                let options = {};
                obj.map((k) => {
                    let i = moment(k.appointmentTime).format("YYYY-M-D");
                    if (options[i]) {
                        options[i].push(k);
                    } else {
                        options[i] = [k];
                    }
                });
                console.log(options)
                console.log(_this.data.currentSelect)
                let list = options[_this.data.currentSelect] || []
                _this.setData({
                    scheduList: options
                })
                console.log(list)
                _this.triggerEvent('change', list)
            })
        },

        // 选中日历
        dayOnSelect(e) {
            let o = e.currentTarget.dataset
            let options = this.data.scheduList
            let full = o.full;
            let list = options[full] || []
            this.setData({
                currentSelect: full,
                selectDay:o,
                showCurrentMonth: `${o.year}年${o.month}月`
            })
            console.log(list)
            this.triggerEvent('change', list)
        },

        // 打开日期选择
        openPicker() {
            this.setData({
                showPopup: true
            })
        },

        // 关闭日期选择
        onClose() {
            this.setData({
                showPopup: false
            })
        },

        // 保存日期选择
        onConfirm(e) {
            console.log(e)
            console.log(this.data.currentSelect)
            let n = this.data.currentSelect
            let y = moment(e.detail).format('YYYY')
            let m = moment(e.detail).format('MM')
            let d = moment(e.detail).format('D')
            let _day = {
                year:y,
                month:m,
                day:d,
                full:`${y}-${m}-${d}`
            }
            console.log(`${y}-${m}-${d}`)
            this.setData({
                showPopup: false,
                currentMonth: e.detail,
                showCurrentMonth: moment(e.detail).format('YYYY年MM月'),
                currentSelect:`${y}-${m}-${d}`,
                selectDay:_day
            })
            this.getSchedules()
            this.updateList(new Date(e.detail), 0, 1)
        },


        // 触摸开始事件  
        touchStart: function (e) {
            touchStartX = e.touches[0].pageX; // 获取触摸时的原点  
            touchStartY = e.touches[0].pageY; // 获取触摸时的原点  
            // 使用js计时器记录时间    
            interval = setInterval(function () {
                time++;
            }, 100);
        },
        // 触摸移动事件  
        touchMove: function (e) {
            touchMoveX = e.touches[0].pageX;
            touchMoveY = e.touches[0].pageY;
        },
        // 触摸结束事件  
        touchEnd: function (e) {
            let _this = this
            var moveX = touchMoveX - touchStartX
            var moveY = touchMoveY - touchStartY
            if (Math.sign(moveX) == -1) {
                moveX = moveX * -1
            }
            if (Math.sign(moveY) == -1) {
                moveY = moveY * -1
            }
            if (moveX <= moveY) { // 上下
                // 向上滑动
                if (touchMoveY - touchStartY <= -30 && time < 10) {
                    console.log("向上滑动")
                    let h = _this.data.swiperHeight
                    let hInterval = setInterval(function () {
                        if (h <= 96) {
                            clearInterval(hInterval)
                            return false;
                        }
                        h -= 26
                        _this.setData({
                            swiperHeight: h
                        })
                    }, 5)
                }
                // 向下滑动  
                if (touchMoveY - touchStartY >= 30 && time < 10) {
                    console.log('向下滑动 ');
                    let h = _this.data.swiperHeight
                    let o = _this.data.dateList1.length / 7 * 98 + 18
                    let hInterval = setInterval(function () {
                        if (h >= o) {
                            clearInterval(hInterval)
                            return false;
                        }
                        h += 26
                        _this.setData({
                            swiperHeight: h
                        })
                    }, 5)
                }
            }
            clearInterval(interval); // 清除setInterval  
            time = 0;
        },

    },
    lifetimes: {
        // 加载事件
        ready() {
            let now = this.data.defaultTime ?
                new Date(this.data.defaultTime) :
                new Date();
            let year = now.getFullYear()
            let month = now.getMonth() + 1
            let day = now.getDate()
            let today = `${year}-${month}-${day}`
            // let selectDay = {
            //     year: year,
            //     month: month,
            //     day:day,
            // };
            this.setData({
                nowDay: {
                    year: year,
                    month: month,
                    day: day,
                },
                currentSelect: today,
                today: today,
                showCurrentMonth: moment(`${year}/${month}/${day}`).format('yyyy年MM月')
            });

            let user = getStorageSync('user');
            this.setData({
                user
            })

            this.getSchedules()

            this.setMonth(year, month, day);
            // this.updateList(now, -1, 0);
            this.updateList(now, 0, 1);
            //this.updateList(now, 1, 2);
            this.setSwiperHeight(1);



        },
    },
    observers: {
        // 重新设置打开状态
        defaultOpen(value) {
            this.setData({
                open: value,
            });
        },
        // // 切换日期
        // changeTime(value) {
        //     // 检测切换日期
        //     if (!value) return;
        //     this.witchDate(new Date(value));
        // },
    },
});